﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using System.IO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using QRCoder;
using System.Drawing;
using System.Configuration;
using System.Web.UI;
using System.Collections;
using uMES.LeanManufacturing.DBUtility;

public partial class uMESFigureDocumentPrintForm : ShopfloorPage, INormalReport
{
    const string QueryWhere = "uMESFigureDocumentPrintForm";
    uMESPartReportingBusiness bll = new uMESPartReportingBusiness();

    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：图文档信息打印申请";
        master.strTitle = "图文档信息打印申请";
        master.ChangeFrame(true);
        NormalReportControl normalCntrl = new NormalReportControl();
        normalCntrl.LtnFirst = lbtnFirst;
        normalCntrl.LtnLast = lbtnLast;
        normalCntrl.LtnNext = lbtnNext;
        normalCntrl.LtnPrev = lbtnPrev;
        normalCntrl.BtnReset = btnReSet;
        normalCntrl.BtnGo = btnGo;
        normalCntrl.BtnSearch = btnSearch;
        normalCntrl.LabPages = lLabel1;
        normalCntrl.TxtPage = txtPage;
        normalCntrl.TxtTotalPage = txtTotalPage;
        normalCntrl.TxtCurrentPage = txtCurrentPage;
        normalCntrl.NormalOperation = this;
        normalCntrl.QueryWhere = QueryWhere;

        WebPanel = WebAsyncRefreshPanel1;

        if (!IsPostBack)
        {
            ClearMessage_PageLoad();
            Session["SelectValue"] = null;
        }
    }

    #region 重置
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        Session["SelectValue"] = null;
    }
    #endregion

    #region 数据查询
    public Dictionary<string, string> GetQuery()
    {
        string strProcessNo = txtProcessNo.Text.Trim();
        string strContainerName = txtContainerName.Text.Trim();
        string strProductName = txtProductName.Text.Trim();
        string strStartDate = txtStartDate.Value.Trim();
        string strEndDate = txtEndDate.Value.Trim();

        Dictionary<string, string> result = new Dictionary<string, string>();
        result.Add("ProcessNo", strProcessNo);
        result.Add("ContainerName", strContainerName);
        result.Add("ProductName", strProductName);
        result.Add("StartDate", strStartDate);
        result.Add("EndDate", strEndDate);

        Session[QueryWhere] = result;

        return result;
    }

    public void QueryData(Dictionary<string, string> query)
    {
        ClearMessage();
        //将当前页面中选择的信息保存至 Session["SelectValue"]  中
        SaveCurrentPageSelectInfo();
        try
        {
            uMESPagingDataDTO result = bll.GeuMESFigureDocumentPrinttSourceData(query, Convert.ToInt32(this.txtCurrentPage.Text), 16);
            this.ItemGrid.DataSource = result.DBTable;
            this.ItemGrid.DataBind();
            this.txtTotalPage.Text = result.PageCount;
            if (result.RowCount == "0")
            {
                this.txtCurrentPage.Text = "0";
            }
            lLabel1.Text = string.Format("第 {0} 页  共 {1} 页", this.txtCurrentPage.Text, this.txtTotalPage.Text);
            this.txtPage.Text = this.txtCurrentPage.Text;
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    protected void SaveCurrentPageSelectInfo()
    {

        DataTable dtAll = new DataTable();

        if (Session["SelectValue"] != null)
        {
            dtAll = (DataTable)Session["SelectValue"];
            Session["SelectValue"] = null;
        }


        foreach (UltraGridColumn col in ItemGrid.Columns)
        {
            if (dtAll.Columns.Contains(col.Key))
                continue;

            dtAll.Columns.Add(col.Key);
        }

        TemplatedColumn temCell = (TemplatedColumn)ItemGrid.Columns.FromKey("ckSelect");

        for (int i = 0; i < temCell.CellItems.Count; i++)
        {
            Infragistics.WebUI.UltraWebGrid.CellItem cellItem = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell.CellItems[i];
            CheckBox ckSelect = (CheckBox)cellItem.FindControl("ckSelect");

            if (ckSelect.Checked == true)
            {
                if (dtAll.Select("productid ='" + ItemGrid.Rows[i].Cells.FromKey("productid").Value + "' AND processno = '" + ItemGrid.Rows[i].Cells.FromKey("processno").Value + "' ").Length > 0)
                {
                    break;
                }
                var dr = dtAll.NewRow();
                foreach (UltraGridColumn col in ItemGrid.Columns)
                {
                
                    dr[col.Key] = ItemGrid.Rows[i].Cells.FromKey(col.Key).Value;
                }
                dtAll.Rows.Add(dr);
            }
        }

        if (dtAll.Rows.Count>0)
        {
            Session["SelectValue"] = dtAll;
        }
     
    }

    public void ResetQuery()
    {
        Session["SelectValue"] = null;
        Session[QueryWhere] = "";
        txtScan.Text = string.Empty;
        txtProcessNo.Text = string.Empty;
        txtContainerName.Text = string.Empty;
        txtProductName.Text = string.Empty;
        txtStartDate.Value = string.Empty;
        txtEndDate.Value = string.Empty;
        ItemGrid.Rows.Clear();

        this.txtTotalPage.Text = "";
        this.txtCurrentPage.Text = "";
        this.txtPage.Text = "";
        lLabel1.Text = "第  页  共  页";
    }
    #endregion

    #region 分页按钮
    protected void lbtnFirst_Click(object sender, EventArgs e)
    {

    }
    protected void lbtnPrev_Click(object sender, EventArgs e)
    {

    }
    protected void lbtnNext_Click(object sender, EventArgs e)
    {

    }
    protected void lbtnLast_Click(object sender, EventArgs e)
    {

    }
    protected void btnGo_Click(object sender, EventArgs e)
    {

    }
    #endregion

    #region 打印按钮
    protected void btnPrint_Click(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            //将当前页面中选择的信息保存至 Session["SelectValue"]  中
            SaveCurrentPageSelectInfo();

            DataTable dtAll = (DataTable)Session["SelectValue"];

            if (dtAll.Rows.Count == 0)
            {
                DisplayMessage("请选择要打印的信息", false);
                return;
            }



            DataSet ds = new DataSet();
            DataTable dtMain = new DataTable();
            dtMain.Columns.Add("ID");//表主键
            dtMain.Columns.Add("ProcessNo");//工作令号
            dtMain.Columns.Add("productname");//产品图号
            dtMain.Columns.Add("description");//图号名称
            dtMain.Columns.Add("productid");//图号ID
            dtMain.Columns.Add("productrevision");//图号版本
            dtMain.Columns.Add("CreateTimes");//生成次数

            DataTable dtDetail = new DataTable();
            dtDetail.Columns.Add("ID");//表主键
            dtDetail.Columns.Add("MainID");//图文档信息打印申请主表ID
            dtDetail.Columns.Add("EmployeeID");//申请人ID
            dtDetail.Columns.Add("EmployeeName");//申请人名称
            dtDetail.Columns.Add("FactoryID");//部门ID
            dtDetail.Columns.Add("FactoryName");//部门名称
            dtDetail.Columns.Add("ApplyDate");//申请时间
            dtDetail.Columns.Add("IsLast");//是否是最新一次生成（0=否1=是）
            dtDetail.Columns.Add("CreateTimes");//生成次数

            ArrayList array = new ArrayList();
            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            int intTimes = 0;

            //创建PDF文档
            Document document = new Document(PageSize.A4, 40, 40, 50, 50);
            string strPath = Server.MapPath(Request.ApplicationPath) + "\\CheckTaskAppendix\\Temp\\";
            string strFileName = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_fff") + ".pdf";
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(strPath + strFileName, FileMode.Create));
            document.Open();

            BaseFont baseFont = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 16);


            for (int i = 0; i < dtAll.Rows.Count; i++)
            {

                intTimes += 1;

                if (intTimes == 1)
                {
                    document.NewPage();
                    PdfPTable table1 = pdfMainTable(baseFont);
                    PdfContentByte cb = writer.DirectContent;

                    Phrase txt = new Phrase("图文档打印申请信息表", font);
                    ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, txt, 300, 800, 0);
                    document.Add(table1);

                }

               
        
                PdfPTable table2 = new PdfPTable(5);
                table2.TotalWidth = 500;
                table2.LockedWidth = true;
                PdfPTable table3 = new PdfPTable(5);
                table3.TotalWidth = 500;
                table3.LockedWidth = true;
                PdfPTable table4 = new PdfPTable(3);
                table4.TotalWidth = 500;
                table4.LockedWidth = true;

                PdfPCell cell1 = new PdfPCell(new Phrase(intTimes.ToString(), font));
                cell1.MinimumHeight = 40;
                cell1.HorizontalAlignment = Element.ALIGN_CENTER;
                cell1.VerticalAlignment = Element.ALIGN_MIDDLE;
                table2.AddCell(cell1);

                PdfPCell cell2 = new PdfPCell(new Phrase(dtAll.Rows[i]["ProcessNo"].ToString(), font));
                cell2.MinimumHeight = 40;
                cell2.HorizontalAlignment = Element.ALIGN_CENTER;
                cell2.VerticalAlignment = Element.ALIGN_MIDDLE;
                table2.AddCell(cell2);

                PdfPCell cell3 = new PdfPCell(new Phrase(dtAll.Rows[i]["ProductName"].ToString(), font));
                cell3.MinimumHeight = 40;
                cell3.HorizontalAlignment = Element.ALIGN_CENTER;
                cell3.VerticalAlignment = Element.ALIGN_MIDDLE;
                table2.AddCell(cell3);

                PdfPCell cell4 = new PdfPCell(new Phrase(dtAll.Rows[i]["Description"].ToString(), font));
                cell4.MinimumHeight = 40;
                cell4.HorizontalAlignment = Element.ALIGN_CENTER;
                cell4.VerticalAlignment = Element.ALIGN_MIDDLE;
                table2.AddCell(cell4);

                PdfPCell cell5 = new PdfPCell(new Phrase(dtAll.Rows[i]["productrevision"].ToString(), font));
                cell5.MinimumHeight = 40;
                cell5.HorizontalAlignment = Element.ALIGN_CENTER;
                cell5.VerticalAlignment = Element.ALIGN_MIDDLE;
                table2.AddCell(cell5);

                document.Add(table2);

                if (intTimes == 16 || i == dtAll.Rows.Count-1)
                {
          
                    for (int g = 0; g < 16 - intTimes; g++)
                    {
                        for (int k = 1; k <= 5; k++)
                        {
                            PdfPCell cell = new PdfPCell(new Phrase("", font));
                            cell.MinimumHeight = 40;
                            cell.HorizontalAlignment = Element.ALIGN_CENTER;
                            cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                            table3.AddCell(cell);
                        }
                    }
                    document.Add(table3);

                    PdfPCell cell11 = new PdfPCell(new Phrase("申请人： " + userInfo["FullName"], font));
                    cell11.MinimumHeight = 30;
                    cell11.HorizontalAlignment = Element.ALIGN_LEFT;
                    cell11.VerticalAlignment = Element.ALIGN_LEFT;
                    table4.AddCell(cell11);

                    PdfPCell cell22 = new PdfPCell(new Phrase("部门：" + userInfo["FactoryName"], font));
                    if (!string.IsNullOrEmpty(userInfo["FactoryDesc"]))
                    {
                        cell22 = new PdfPCell(new Phrase("部门：" + userInfo["FactoryDesc"], font));
                    }

                    cell22.MinimumHeight = 30;
                    cell22.HorizontalAlignment = Element.ALIGN_LEFT;
                    cell22.VerticalAlignment = Element.ALIGN_LEFT;
                    table4.AddCell(cell22);


                    PdfPCell cell33 = new PdfPCell(new Phrase("申请时间：" + System.DateTime.Now.ToString("yyyy-MM-dd"), font));
                    cell33.MinimumHeight = 30;
                    cell33.HorizontalAlignment = Element.ALIGN_LEFT;
                    cell33.VerticalAlignment = Element.ALIGN_LEFT;
                    table4.AddCell(cell33);
                    document.Add(table4);

                    intTimes = 0;

                }

                string strID = string.Empty;
                if (!string.IsNullOrEmpty(dtAll.Rows[i]["ID"].ToString()))
                {
                    strID = dtAll.Rows[i]["ID"].ToString();
                    array.Add("Update FigureDocumentPrintingInfo fpi SET fpi.CreateTimes =" + (int.Parse(dtAll.Rows[i]["createtimes"].ToString()) + 1) + " WHERE fpi.id='" + dtAll.Rows[i]["ID"].ToString() + "'");
                    array.Add("Update FigureDocumentPrintDetailInfo fpdi SET fpdi.IsLast =0 WHERE fpdi.MainID='" + dtAll.Rows[i]["ID"].ToString() + "'");
                    dtDetail.Rows.Add();
                    dtDetail.Rows[dtDetail.Rows.Count - 1]["MainID"] = dtAll.Rows[i]["ID"].ToString() + "㊣String";//图文档信息打印申请主表ID
                }
                else
                {
                    dtMain.Rows.Add();
                    dtMain.Rows[dtMain.Rows.Count - 1]["ID"] = Guid.NewGuid().ToString() + "㊣String"; //表主键
                    dtMain.Rows[dtMain.Rows.Count - 1]["ProcessNo"] = dtAll.Rows[i]["ProcessNo"].ToString() + "㊣String";//工作令号
                    dtMain.Rows[dtMain.Rows.Count - 1]["productname"] = dtAll.Rows[i]["ProductName"].ToString() + "㊣String";//产品图号
                    dtMain.Rows[dtMain.Rows.Count - 1]["description"] = dtAll.Rows[i]["Description"].ToString() + "㊣String";//图号名称
                    dtMain.Rows[dtMain.Rows.Count - 1]["productid"] = dtAll.Rows[i]["productid"].ToString() + "㊣String";//图号ID
                    dtMain.Rows[dtMain.Rows.Count - 1]["productrevision"] = dtAll.Rows[i]["productrevision"].ToString() + "㊣String";//图号版本
                    dtMain.Rows[dtMain.Rows.Count - 1]["CreateTimes"] = (int.Parse(dtAll.Rows[i]["createtimes"].ToString()) + 1) + "㊣Integer";//生成次数

                    dtDetail.Rows.Add();
                    dtDetail.Rows[dtDetail.Rows.Count - 1]["MainID"] = dtMain.Rows[dtMain.Rows.Count - 1]["ID"].ToString() + "㊣String";//图文档信息打印申请主表ID
                }


          
                dtDetail.Rows[dtDetail.Rows.Count - 1]["ID"] = Guid.NewGuid().ToString() + "㊣String";//表主键

                dtDetail.Rows[dtDetail.Rows.Count - 1]["EmployeeID"] = userInfo["EmployeeID"] + "㊣String";//申请人ID
                dtDetail.Rows[dtDetail.Rows.Count - 1]["EmployeeName"] = userInfo["FullName"] + "㊣String";//申请人名称
                dtDetail.Rows[dtDetail.Rows.Count - 1]["FactoryID"] = userInfo["FactoryID"] + "㊣String";//部门ID
                dtDetail.Rows[dtDetail.Rows.Count - 1]["FactoryName"] = userInfo["FactoryName"] + "㊣String";//部门名称
                if (!string.IsNullOrEmpty(userInfo["FactoryDesc"]))
                {
                    dtDetail.Rows[dtDetail.Rows.Count - 1]["FactoryName"] = userInfo["FactoryDesc"] + "㊣String";//部门名称
                }


                dtDetail.Rows[dtDetail.Rows.Count - 1]["ApplyDate"] = System.DateTime.Now + "㊣Date"; ;//申请时间
                dtDetail.Rows[dtDetail.Rows.Count - 1]["IsLast"] = 1 + "㊣Integer";//是否是最新一次生成（0=否1=是）
                dtDetail.Rows[dtDetail.Rows.Count - 1]["CreateTimes"] = (int.Parse(dtAll.Rows[i]["createtimes"].ToString()) + 1) + "㊣Integer";//生成次数

            }

            document.Close();
            writer.Close();

            string strScript = "<script>window.open('../../CheckTaskAppendix/Temp/" + strFileName + "');</script>";
            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);


            dtMain.Rows.Add();
            dtMain.Rows[dtMain.Rows.Count - 1]["ID"] = "" + "㊣String";

            ds.Tables.Add(dtMain);
            ds.Tables[ds.Tables.Count - 1].TableName = "FigureDocumentPrintingInfo" + "㊣ID";

            dtDetail.Rows.Add();
            dtDetail.Rows[dtDetail.Rows.Count - 1]["ID"] = "" + "㊣String";

            ds.Tables.Add(dtDetail);
            ds.Tables[ds.Tables.Count - 1].TableName = "FigureDocumentPrintDetailInfo" + "㊣ID";

            //保存数据
            Dictionary<string, object> para = new Dictionary<string, object>();
            para.Add("dsData", ds);
            string strMessage = string.Empty;
            if (array.Count > 0)
            {
                OracleHelper.ExecuteSqlTran(array);
            }
            bool result = bll.SaveDataToDatabaseNew(para, out strMessage);
            ResetQuery();
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }
    #endregion


    #region 工序列表表头
    /// <summary>
    /// 工序列表表头
    /// </summary>
    /// <param name="baseFont"></param>
    /// <returns></returns>
    protected PdfPTable pdfMainTable(BaseFont baseFont)
    {
        PdfPTable table = new PdfPTable(5);
        table.TotalWidth = 500;
        table.LockedWidth = true;

        iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 12);
        PdfPCell cell = new PdfPCell(new Phrase("序号", font));
        cell.MinimumHeight = 40;
        cell.HorizontalAlignment = Element.ALIGN_CENTER;
        cell.VerticalAlignment = Element.ALIGN_MIDDLE;
        table.AddCell(cell);
        cell = new PdfPCell(new Phrase("工作令号", font));
        cell.MinimumHeight = 40;
        cell.HorizontalAlignment = Element.ALIGN_CENTER;
        cell.VerticalAlignment = Element.ALIGN_MIDDLE;
        table.AddCell(cell);
        cell = new PdfPCell(new Phrase("图号", font));
        cell.MinimumHeight = 40;
        cell.HorizontalAlignment = Element.ALIGN_CENTER;
        cell.VerticalAlignment = Element.ALIGN_MIDDLE;
        table.AddCell(cell);
        cell = new PdfPCell(new Phrase("名称", font));
        cell.MinimumHeight = 40;
        cell.HorizontalAlignment = Element.ALIGN_CENTER;
        cell.VerticalAlignment = Element.ALIGN_MIDDLE;
        table.AddCell(cell);
        cell = new PdfPCell(new Phrase("版本", font));
        cell.MinimumHeight = 40;
        cell.HorizontalAlignment = Element.ALIGN_CENTER;
        cell.VerticalAlignment = Element.ALIGN_MIDDLE;
        table.AddCell(cell);

        return table;
    }
    #endregion

    #region 过程检验流程卡主表格
    /// <summary>
    /// 过程检验流程卡主表格
    /// </summary>
    /// <param name="baseFont"></param>
    /// <returns></returns>
    protected PdfPTable pdfMainTable(BaseFont baseFont, int i)
    {
        PdfPTable table = new PdfPTable(new float[] { 70, 96, 70, 96, 70, 98 });
        table.TotalWidth = 500;
        table.LockedWidth = true;

        PdfPCell cell;
        iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 12);
        cell = new PdfPCell(new Phrase("序号", font));
        cell.MinimumHeight = 40;
        cell.HorizontalAlignment = Element.ALIGN_CENTER;
        cell.VerticalAlignment = Element.ALIGN_MIDDLE;
        table.AddCell(cell);

        font = new iTextSharp.text.Font(baseFont, 12);
        cell = new PdfPCell(new Phrase("工作令号", font));
        cell.MinimumHeight = 40;
        cell.HorizontalAlignment = Element.ALIGN_CENTER;
        cell.VerticalAlignment = Element.ALIGN_MIDDLE;
        table.AddCell(cell);

        cell = new PdfPCell(new Phrase("图号", font));
        cell.MinimumHeight = 40;
        cell.HorizontalAlignment = Element.ALIGN_CENTER;
        cell.VerticalAlignment = Element.ALIGN_MIDDLE;
        table.AddCell(cell);

        font = new iTextSharp.text.Font(baseFont, 12);
        cell = new PdfPCell(new Phrase("名称", font));
        cell.MinimumHeight = 40;
        cell.HorizontalAlignment = Element.ALIGN_CENTER;
        cell.VerticalAlignment = Element.ALIGN_MIDDLE;
        table.AddCell(cell);

        font = new iTextSharp.text.Font(baseFont, 12);
        cell = new PdfPCell(new Phrase("版本", font));
        cell.MinimumHeight = 40;
        cell.HorizontalAlignment = Element.ALIGN_CENTER;
        cell.VerticalAlignment = Element.ALIGN_MIDDLE;
        table.AddCell(cell);


        return table;
    }
    #endregion

    protected void txtScan_TextChanged(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            string strScan = txtScan.Text.Trim();
            txtScan.Text = "";

            if (strScan != string.Empty)
            {
                Dictionary<string, string> para = new Dictionary<string, string>();
                para.Add("ScanContainerName", strScan);

                Session[QueryWhere] = para;

                txtCurrentPage.Text = "1";
                QueryData(para);
            }
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    protected void btnSelectAll_Click(object sender, EventArgs e)
    {
        if (btnSelectAll.Text == "全选")
        {
            btnSelectAll.Text = "全不选";
            uMESCommonFunction.ResetGridCheckStatus2(ItemGrid, "ckSelect", 0);
        }
        else if (btnSelectAll.Text == "全不选")
        {
            btnSelectAll.Text = "全选";
            uMESCommonFunction.ResetGridCheckStatus2(ItemGrid, "ckSelect", 2);
        }

    }

    protected void btnInRevert_Click(object sender, EventArgs e)
    {
        uMESCommonFunction.ResetGridCheckStatus2(ItemGrid, "ckSelect", 1);
    }
}